package admin

import (
	"fmt"
	"ginBasic/app/common/business"
	"ginBasic/app/common/lib"
	"github.com/gin-gonic/gin"
	"net/http"
)

type RoleController struct {
	BaseController
}

func (con RoleController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/index.html", gin.H{})
	return
}

// 获取列表数据
func (con RoleController) GetList(c *gin.Context) {
	roleList := business.Role.RoleList()
	con.Show(0, 1000, roleList, "查询成功", c)
	return
}

func (con RoleController) Add(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/role/add.html", gin.H{})
	return
}

func (con RoleController) DoAdd(c *gin.Context) {

	res, msg := business.Role.DoAddRole(c)
	if !res {
		con.ShowRes(-1, msg, c)
		return
	} else {
		con.ShowRes(0, msg, c)
		return
	}
}

func (con RoleController) Edit(c *gin.Context) {
	id, _ := lib.Int(c.Query("id"))
	info := business.Role.GetRoleDetail(id)
	fmt.Println("info:", info)
	c.HTML(http.StatusOK, "admin/role/edit.html", gin.H{
		"info": info,
	})
}

func (con RoleController) DoEdit(c *gin.Context) {
	res, msg := business.Role.DoEditRole(c)
	if !res {
		con.ShowRes(-1, msg, c)
		return
	} else {
		con.ShowRes(0, msg, c)
		return
	}
}

func (con RoleController) Del(c *gin.Context) {
	ids := c.Query("ids")
	if ids == "" {
		con.ShowRes(-1, "记录ID不能为空", c)
	}
	count, err := business.Role.DeleteRole(ids)
	if err != nil {
		con.ShowRes(-1, err.Error(), c)
		return
	} else {
		con.ShowRes(0, "成功删除"+lib.String(int(count))+"条数据", c)
		return
	}
}

func (con RoleController) Status(c *gin.Context) {
	res, msg := business.Role.UpdateRoleStatus(c)
	if !res {
		con.ShowRes(-1, msg, c)
		return
	} else {
		con.ShowRes(0, msg, c)
		return
	}
}

func (con RoleController) Auth(c *gin.Context) {
	id, _ := lib.Int(c.Query("id"))
	list := business.Role.GetAuthList(id)
	c.HTML(http.StatusOK, "admin/role/auth.html", gin.H{
		"data": list,
		"id":   id,
	})
}

func (con RoleController) DoAuth(c *gin.Context) {
	if c.Request.Method != "POST" {
		con.ShowRes(-1, "请求方式有误", c)
		return
	}
	id, _ := lib.Int(c.PostForm("id"))
	accessIds := c.PostForm("accessIds")
	if accessIds == "" {
		con.ShowRes(-1, "请选择权限菜单", c)
		return
	}
	_, err := business.Role.SaveRoleAndAccess(id, accessIds)
	if err != nil {
		con.ShowRes(-1, err.Error(), c)
		return
	} else {
		con.ShowRes(0, "设置权限成功", c)
		return
	}
}
